import { useState, useRef } from 'react'
import { Modal, Form, Button, message, Space, FormInstance } from 'antd';
import Upload, { uploadFile } from '@src/components/upload'
import { uploadTemplateRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool';

const { Item } = Form

async function onFinish (d: { [k: string]: any }, meetingid: string, hide: () => void, refreshFn: () => void) {
  let fileid = ''
  if (d.file instanceof Array && d.file.length > 0) {
    const files = await uploadFile(d.file)
    fileid = files.map(li => li.id).join()
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(uploadTemplateRequest(meetingid, fileid))
  h()
  if (e === null) {
    refreshFn()
    hide()
  }
}

interface Props {
  visible: boolean
  meetingid: string
  hide: () => void
  refreshFn: () => void
}

function Main ({ visible, meetingid, hide, refreshFn }: Props) {
  const fromRef = useRef<FormInstance>(null)
  return (
    <Modal
      title='上传笔录'
      visible={visible}
      onCancel={() => hide()}
      footer={(
        <Space>
          <Button onClick={() => hide()}>取消</Button>
          <Button type='primary' onClick={() => fromRef.current?.submit()}>确定</Button>
        </Space>
      )}
      destroyOnClose
    >
      <Form ref={fromRef} onFinish={d => onFinish(d, meetingid, hide, refreshFn)}>
        <Item name='file' label='线上签字笔录文件' rules={[{ required: true, message: '线上签字笔录文件不能为空' }]}>
          <Upload accept='.docx' maxLength={1} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
